package com.comunicacion2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	static final int PUNTO_REQ = 2;
	static final int REDES_REQ = 1;
	EditText etRed;
	ListView list;
	ArrayList<Punto> puntos = new ArrayList<Punto>();
	ArrayAdapter<Punto> adapter;
	ActionMode mActionMode;

	private static int selectedItem = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			this.onRestoreInstanceState(savedInstanceState);
		}
		setContentView(R.layout.activity_main);

		etRed = (EditText) findViewById(R.id.text_red);
		list = (ListView) findViewById(R.id.list_puntos);

		// puntos = new ArrayList<Punto>();
		adapter = new ArrayAdapter<Punto>(this,
				android.R.layout.simple_list_item_1, puntos);
		list.setAdapter(adapter);

		// list.setOnItemLongClickListener(new OnItemLongClickListener() {
		//
		// @Override
		// public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
		// int arg2, long arg3) {
		// deletePuntoList(puntos.get(arg2));
		// return false;
		// }
		// });

		list.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (mActionMode != null) {
					return false;
				}
				selectedItem = position;

				// start the CAB using the ActionMode.Callback defined above
				mActionMode = MainActivity.this
						.startActionMode(mActionModeCallback);
				view.setSelected(true);
				return true;
			}
		});

		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	// public void setModeListViewDelete(ListView list) {
	//
	// }

	public void agregarPunto(View view) {
		if (etRed.length() != 0) {
			Intent intent = new Intent(this, AgregarPuntoActivity.class);
			intent.putExtra("Red", etRed.getText().toString());
			startActivityForResult(intent, PUNTO_REQ);
		} else {
			Toast.makeText(this, "No se ha seleccionado una red",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void seleccionarRed(View view) {
		Intent intent = new Intent(this, SelectorRedesActivity.class);
		startActivityForResult(intent, REDES_REQ);
	}

	public void addPuntoList(Punto punto) {
		puntos.add(punto);
		adapter.notifyDataSetChanged();
	}

	public void deletePuntoList(Punto punto) {
		puntos.remove(punto);
		adapter.notifyDataSetChanged();
		selectedItem = -1;
	}

	public void exportarListaPuntos(View view) {

		String data = Punto.CSV_HEADERS + "\n";
		for (Punto punto : puntos) {
			data += punto.toCsv() + "\n";
		}
		try {
			File file = new File(Environment.getExternalStorageDirectory(),
					"fingerprints.csv");
			FileOutputStream fos = new FileOutputStream(file);
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
			outputStreamWriter.write(data);
			outputStreamWriter.close();
			Toast.makeText(
					this,
					"Los datos se almacenaron correctamente en "
							+ Environment.getExternalStorageDirectory()
							+ "fingerprints.csv", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			Log.e("Exception", "File write failed: " + e.toString());
			Toast.makeText(this, "ERROR: Los datos no fueron almacenados",
					Toast.LENGTH_SHORT).show();
		}
	}

	private Punto bundleToPunto(Bundle b) {
		String id = b.getString("Id");
		String X = b.getString("X");
		String Y = b.getString("Y");
		String intensidad = b.getString("Intensidad");
		String tiempoViajePaq = b.getString("TiempoViajePaq");
		return new Punto(id, X, Y, intensidad, tiempoViajePaq);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		// Para
		if (requestCode == PUNTO_REQ) {
			if (resultCode == RESULT_OK) {
				Bundle b = data.getBundleExtra("RESULTADO");
				this.addPuntoList(this.bundleToPunto(b));
			}
		} else if (requestCode == REDES_REQ) {
			if (resultCode == RESULT_OK) {
				EditText et_red = (EditText) findViewById(R.id.text_red);
				et_red.setText(data.getStringExtra("Red"));
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putSerializable("ListaRedes", puntos);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		puntos = (ArrayList<Punto>) savedInstanceState
				.getSerializable("ListaRedes");
	}

	private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

		// Called when the action mode is created; startActionMode() was called
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			// Inflate a menu resource providing context menu items
			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate(R.menu.borrar_punto, menu);
			return true;
		}

		// Called each time the action mode is shown. Always called after
		// onCreateActionMode, but
		// may be called multiple times if the mode is invalidated.
		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false; // Return false if nothing is done
		}

		// Called when the user selects a contextual menu item
		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			switch (item.getItemId()) {
			case R.id.delete_punto:
				deletePuntoList(puntos.get(selectedItem));
				mode.finish(); // Action picked, so close the CAB
				return true;
			default:
				return false;
			}
		}

		// Called when the user exits the action mode
		@Override
		public void onDestroyActionMode(ActionMode mode) {
			mActionMode = null;
			selectedItem = -1;
		}
	};

}
